#!/bin/bash -e

set -e

# Grow the last partition to the last of the disk.

ROOTDEV=
ROOTPART=
ROOTTYPE=
PARTNUM=

echo "[+] Preparing to grow..."

if [ "$(mount | grep 'on / type' | grep nfs)" ]; then
	echo "[-] No joking around, please. You are using a NFS."
	exit 1
fi

if [ "$1" == "yes-please" ]; then
	echo "[+] You said yes, so we just go on."
elif [ -t 0 -a -t 1 ]; then
	read -p "Are you sure (y/N)? " ANS
	if ! echo "$ANS" | grep -q '[yY]' ; then
		echo "[+] Aborting."
		exit 0
	fi
	echo "[+] Okay, you choose to take the risk."
else
	echo "[+] You are running this with scripts. You have taken the risk."
fi

if [ -e "/.resize-partition" ]; then
	# Resize partition
	source "/.resize-partition"
	case "$ROOTTYPE" in
		"ext4")
			resize2fs /dev/$ROOTPART
			;;
		"btrfs")
			btrfs filesystem resize max /
			;;
		*)
			;;
	esac
	rm /.resize-partition
	exit 0	
else
	ROOTPART=$(lsblk -lno NAME,MOUNTPOINT | sed -E 's/\s+/,/g' | grep ',/$' | cut -d',' -f1)
	ROOTDEV="/dev/$(lsblk -lno PKNAME /dev/$ROOTPART)"
	ROOTTYPE=$(lsblk -lno FSTYPE /dev/$ROOTPART)
	# Get current partition number
	# PARTNUM=$(lsblk -lno "MAJ:MIN" /dev/$ROOTPART | cut -d':' -f2) - It is not reliable
	# Use the old school method
	PARTNUMS=($(echo "$ROOTPART" | grep -oE '[0-9]+'))
	PARTNUM=${PARTNUMS[-1]}
	echo "[+] Root partition: $ROOTPART"
	echo "[+] Device the root partition is in: $ROOTDEV"
	echo "[+] Root filesystem: $ROOTTYPE"
	echo "[+] Number of the root partition: $PARTNUM"
	if [ "$DEBUG" ]; then
		echo "[D] That's all we need to know."
		exit 0
	fi
	if [ "$ROOTDEV" -a "$ROOTPART" -a "$ROOTTYPE" -a "$PARTNUM" ]; then
		# Get partitions
		PARTS=($(lsblk -o NAME -ln $ROOTDEV))
		echo "[+] Last partition of this disk: ${PARTS[-1]}"
		if [ "$ROOTPART" != "${PARTS[-1]}" ]; then
			echo "[-] Jesus, don't even think about it; Your partition is not the last partition!"
			exit 1
		fi
		echo "[+] Okay, your root partition is the last partition. Proceeding."
		# Resize partition
		# Call sfdisk to grow this partition, gently
		# It will not touch anything else.
		echo ', +' | sfdisk --force -N $PARTNUM $ROOTDEV
		# Okay, we are ready to grow
		touch "/.resize-partition"
		echo "ROOTDEV=$ROOTDEV" >> /.resize-partition
		echo "ROOTPART=$ROOTPART" >> /.resize-partition
		echo "ROOTTYPE=$ROOTTYPE" >> /.resize-partition
		echo "PARTNUM=$PARTNUM" >> /.resize-partition
	fi
fi

